package com.zjc.netty.server;

import com.zjc.netty.server.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Component
public class NettyServer {

    private final Logger log = LoggerFactory.getLogger(NettyServer.class);

    private NioEventLoopGroup p;
    private NioEventLoopGroup c;

    @Value("${port:7066}")
    private int port = 7066;

    public void start() {
        p = new NioEventLoopGroup();
        c = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(p, c)
                .channel(NioServerSocketChannel.class)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65533, 0, 2, 0, 2));
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new LengthFieldPrepender(2));
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new EchoServerHandler());
                    }
                });

        try {
            ChannelFuture f = serverBootstrap.bind(port).sync();

            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void shutdown() {
        log.info("Stopping server!");
        if (c != null) {
            final Future<?> workerFinished = c.shutdownGracefully(2, 10, TimeUnit.SECONDS);
            workerFinished.syncUninterruptibly();

        }
        if (p != null) {
            final Future<?> bossFinished = p.shutdownGracefully(2, 10, TimeUnit.SECONDS);
            bossFinished.syncUninterruptibly();
        }

        log.info("Server stopped!");
    }

}
